#!/usr/bin/bash

FILE=$(readlink -f "${BASH_SOURCE[0]}")
CDIR=$(dirname "$FILE")
NAME=$(basename "$FILE")
TMPDIR=${TMPDIR:-"/tmp"}

function get_var
{
    typeset config_file=${1?"*** config file, e.g. minicfg.json"}
    typeset var_name=${2?"*** var name, e.g. server_ip"}
    cat $config_file | jq .${var_name} | xargs echo
}

function check_var
{
    typeset name=${1?"*** var name, e.g. server_ip"}
    typeset value=""
    eval "value=\$${name}"
    [[ $value == "null" ]] && value="" # XXX: YAML: null -> bash: ""
    [[ -z $value ]] && return 1 || return 0
}

minicfg=${1?"*** minicfg  file (JSON)"}
tonecfg=${2?"*** template file (YAML)"}

db_password=$(get_var           ${minicfg} "db_password")
redis_password=$(get_var        ${minicfg} "redis_password")
tone_storage_password=$(get_var ${minicfg} "tone_storage_password")
toneagent_access_key=$(get_var  ${minicfg} "toneagent_access_key")
toneagent_secret_key=$(get_var  ${minicfg} "toneagent_secret_key")
admin_urls_token=$(get_var      ${minicfg} "admin_urls_token")
pub_api_token=$(get_var         ${minicfg} "pub_api_token")
version_tag=$(get_var           ${minicfg} "version_tag")
server_ip=$(get_var             ${minicfg} "server_ip")

check_var "server_ip"
(( $? != 0 )) && echo "Oops, var 'server_ip' not set" >&2 && exit 1

cat ${tonecfg} | sed -e "s/var_db_password/${db_password}/g"                     \
                     -e "s/var_redis_password/${redis_password}/g"               \
                     -e "s/var_tone_storage_password/${tone_storage_password}/g" \
                     -e "s/var_toneagent_access_key/${toneagent_access_key}/g"   \
                     -e "s/var_toneagent_secret_key/${toneagent_secret_key}/g"   \
                     -e "s/var_admin_urls_token/${admin_urls_token}/g"           \
                     -e "s/var_pub_api_token/${pub_api_token}/g"                 \
                     -e "s/var_version_tag/${version_tag}/g"                     \
                     -e "s/var_server_ip/${server_ip}/g"                         \
                     -e "s%image: wurstmeister/zookeeper*%image: wurstmeister/zookeeper:latest%" \
                     -e "s%image: tone-storage*%image: tone-storage:latest%" \
                     -e "s%^version:%#version:%"

# XXX: Append one '\n' on purpose because the template does not have
echo
